"use strict";
/**
 * 获取喜马拉雅 资源
 */
Object.defineProperty(exports, "__esModule", { value: true });
const R = require("request");
const cheerio = require("cheerio");
const fs = require("fs");
let url = 'http://www.ximalaya.com/13609695/album/2868786';
let sound_ids = [];
function getSoundIds(url) {
    return new Promise(function (resolve, reject) {
        R.get(url, function (error, res, data) {
            if (error) {
                reject(error);
            }
            else {
                let $ = cheerio.load(data);
                let sound_ids = $('.personal_body').attr('sound_ids').split(',');
                resolve(sound_ids);
            }
        });
    });
}
let dir = './audio/';
// 下载数据
function download(id) {
    let baseUrl = "http://www.ximalaya.com/tracks/" + id + '.json';
    return new Promise((resolve, reject) => {
        R.get(baseUrl, function (error, res, data) {
            if (error) {
                reject(error);
            }
            data = JSON.parse(data);
            const path = data.play_path_64;
            const title = data.title;
            console.log("正在下载 <<" + title + ">>");
            R.get(path, {
                headers: {
                    "Content-type": "application/octet-stream"
                }
            })
                .pipe(fs.createWriteStream(dir + title + ".m4a")
                .on('close', () => resolve(title + " 下载完成")));
        });
    });
}
async function run() {
    let sound_ids = await getSoundIds(url);
    for (let id in sound_ids) {
        let log = await download(sound_ids[id]);
        console.log(log);
    }
}
run();
